package com.exam.api.common.web;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author iaa
 * @Description: 将包装类包装为包装体
 * @Date 2024/3/1 13:56
 * @Version: 1.0
 */
@ControllerAdvice(
    annotations = {RestController.class}
)
public class TinyResponseHandler implements ResponseBodyAdvice<Object> {
    private static final Logger log = LoggerFactory.getLogger(TinyResponseHandler.class);

    public TinyResponseHandler() {
    }
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        TinyResponse attribute = (TinyResponse)request.getAttribute("RESPONSE-WRAPPER-ANN");
        log.trace("判断接口{}是否有包装注解:{}", request.getRequestURI(), attribute != null);
        return attribute != null;
    }
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof Exception) {
            return body;
        } else {
            log.trace("返回结果包装");
            return ResultData.success(body);
        }
    }
}
